package com.mystudy.management.usermanagement.config;

import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.thymeleaf.dialect.SaTokenDialect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

//声明为配置文件
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        //注册Sa-Token的路由拦截器
        registry.addInterceptor( new SaRouteInterceptor((req,res,handler)->{
                    SaRouter.match("/admin/index/**").check(r -> StpUtil.checkLogin()).stop();//登录检查
        }))
                .addPathPatterns("/admin/index/**");//拦截路径

    }


    //注册Thymeleaf标签方言对象
    @Bean
    public SaTokenDialect getSaTokenDialect() {
        return new SaTokenDialect();
    }


    // 为 Thymeleaf 注入全局变量，以便在页面中调用 Sa-Token 的方法
    @Autowired
    private void configureThymeleafStaticVars(ThymeleafViewResolver viewResolver) {
        viewResolver.addStaticVariable("stp", StpUtil.stpLogic);
    }

}
